// pages/article/detail/detail.js
import {
  DETAIL,
  PROJECT_COMMENT_LIST,
  PROJECT_COMMENT_PUSH,
  USER_RELATION_REVERSE,
  FAVORITE_REVERSE,
} from "../../../request/api";
import {
  html2json
} from "../../../utils/htmlToWxml";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    ident: '',
    type: 0,
    key: '',
    result: {},
    newsData: {},
    commentList: [],
    hiddenmodalput: true,
    commentContent: '',
    replyId: 0,
    reAuthorId: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var id = options.id;
    that.data.id = id;
    that.data.ident = options.ident;
    that.data.type = options.type || 1;
    var key = 'osc_1_0';
    that.data.key = key;
    this.getDetail(id, options.ident, options.type, key);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: that.getShareTitle(), // 默认是小程序的名称(可以写slogan等)
      path: '/pages/project/detail/detail?id=' + that.data.id + '&type=' + that.data.type, // 默认是当前页面，必须是以‘/’开头的完整路径
      // imageUrl: '', //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
    };
    return shareObj;
  },

  onShareTimeline: function(){
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: that.getShareTitle(), // 默认是小程序的名称(可以写slogan等)
      query: 'id=' + that.data.id + '&type=' + that.data.type, //当前页面路径携带的参数
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
    };
    return shareObj;
  },

  getShareTitle: function(){
    var userInfo = getApp().globalData.userInfo;
    var userName;
    if(userInfo){
      userName = userInfo.name || '有人';
    } else {
      userName = '有人';
    }
    var title = userName + '分享了一篇文章';
    return title;
  },

  stockClick: function (e) {
    var secCode = e.currentTarget.dataset.seccode;
    var secName = e.currentTarget.dataset.secname;
    console.log("stockClick:" + secCode + ";secName:" + secName);
  },
  imageLoad: function (e) {
    var width = e.detail.width;
    var height = e.detail.height;
    var windowWidth = wx.getSystemInfoSync().windowWidth - 30;
    var picHeight = (height / width) * windowWidth;
    var index = e.currentTarget.dataset.index;
    this.data.newsData[index].attr.height = picHeight;
    this.setData({
      newsData: this.data.newsData
    });
  },

  getDetail: function (id, ident, type, key) {
    wx.showLoading({
      title: '正在加载',
    });
    var param;
    if(id){
      param = {
        'id': id,
        'type': type,
      };
    } else {
      param = {
        'ident': ident,
        'type': type,
        'key': key
      };
    }
    DETAIL(param).then(res => {
      if (res.data.code == 1) {
        var newsDetail = html2json(res.data.result.body.replaceAll("&nbsp;", ''));
        console.log('---newsDetail = ' + newsDetail);
        id = res.data.result.id;
        this.setData({
          id: id,
          result: res.data.result,
          newsData: newsDetail,
        });

        this.getHot5Comments(id, 2, 'refer,reply', type, '');
      }
      wx.hideLoading({
        success: (res) => {},
      });
    }).catch(err => {
      wx.hideLoading({
        success: (res) => {},
      });
    });
  },

  getHot5Comments: function (id, order, parts, type, pageToken) {
    PROJECT_COMMENT_LIST({
      'sourceId': id,
      'order': order,
      'parts': parts,
      'type': type,
      'pageToken': pageToken,
    }).then(res => {
      if (res.data.code == 1) {
        this.setData({
          commentList: res.data.result.items,
        });
      }
    }).catch(err => {

    });
  },

  submitComment: function(id, replyId, reAuthorId, type, content){
    wx.showLoading({
      title: '正在提交...',
    });
    PROJECT_COMMENT_PUSH({
      'sourceId': id,
      'replyId': replyId,
      'reAuthorId': reAuthorId,
      'type': type,
      'content': content,
    }).then(res => {
      wx.hideLoading({
        success: (res) => {},
      });
      this.showTips(res.data.message);
    }).catch(err => {
      wx.hideLoading({
        success: (res) => {},
      });
      this.showTips("评论失败");
    });
  },

  relationReverse: function (e) {
    USER_RELATION_REVERSE({
      'id': this.data.result.author.id
    }).then(res => {
      var relation = res.data.result.relation;
      var result = this.data.result;
      result.author.relation = relation;
      this.setData({
        result: result,
      })
      this.showTips(relation == 2 ? "关注成功" : "取消关注");

    }).catch(err => {

    });
  },

  favoriteReverse: function (e) {
    if (!this.checkLogin()) {
      return;
    }
    FAVORITE_REVERSE({
      'id': this.data.id,
      'type': this.data.type
    }).then(res => {
      var favorite = res.data.result.favorite;
      var result = this.data.result;
      result.favorite = favorite;
      this.setData({
        result: result,
      });
    }).catch(err => {

    });
  },

  toCommentList: function () {
    wx.navigateTo({
      url: '/pages/comment/comment?id=' + this.data.id + '&type=' + this.data.type,
    })
  },
  toUserProfile: function(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/user/user?userId='+id,
    })
  },

  showCommentInput: function () {
    if(!getApp().globalData.versionCheckPassed){
      this.showTips('暂不支持评论');
      return;
    }
    if (!this.checkLogin()) {
      return;
    }
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput,
    })
  },

  //取消按钮
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },

  //确认
  confirm: function () {
    if(this.data.commentContent.length == 0){
      this.showTips('请输入评论内容');
      return;
    }
    this.submitComment(this.data.id, this.data.replyId, this.data.reAuthorId, this.data.type, this.data.commentContent);
    this.setData({
      hiddenmodalput: true,
    });
  },

  inputChange: function(e){
    this.data.commentContent = e.detail.value;
  },


  showTips: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  },

  checkLogin: function () {
    var app = getApp();
    if (!app.globalData.isLogin) {
      wx.showModal({
        content: '您还没有登录，请登录',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/account/login/login',
            });
          } else if (res.cancel) {

          }
        }
      });
      return false;
    } else {
      return true;
    }
  }
})